package 设计模式.prototype.deepclone;

import java.io.*;

public class DeepProtoType implements Serializable,Cloneable {
    public String name;
    public DeepCloneableTarget deepCloneableTarget;
    public DeepProtoType(){
        super();
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep=null;
        deep=super.clone();
        DeepProtoType deepProtoType=(DeepProtoType) deep;
        deepProtoType.deepCloneableTarget=(DeepCloneableTarget) deepCloneableTarget.clone();
        return deepProtoType;
    }

    public Object deepClone(){
        ByteArrayOutputStream bos=null;
        ObjectOutputStream oos=null;
        ByteArrayInputStream bis=null;
        ObjectInputStream ois=null;

        try{
            bos=new ByteArrayOutputStream();
            oos=new ObjectOutputStream(bos);
            oos.writeObject(this);//读对象放入字节，

            bis=new ByteArrayInputStream(bos.toByteArray());
            ois=new ObjectInputStream(bis);
            DeepProtoType deepProtoType = (DeepProtoType) ois.readObject();
            return deepProtoType;
        } catch (Exception e) {
            e.getMessage();
            return null;
        }finally {
            try {
                bos.close();
                oos.close();
                ois.close();
                bis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }

    }
}
